﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using BrnMall.Business;
using BrnMall.Manager.Domain.Restaurant;
using BrnMall.Manager.Manager.Restaurant;
using BrnMall.Manager.Manager.WeApp;
using BrnMall.Services;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Models;

namespace BrnMall.Web.StoreAdmin.controllers
{
    public class RestaurantController : BaseStoreAdminController
    {
        #region 排队
        public ActionResult LineItemList()
        {
            var list = LineManager.GetStoreLineItems(WorkContext.StoreId);
            var listModel = list.Select(t =>
             new LineItemModel
             {
                 CurrNumber = t.CurrNumber,
                 DisplayOrder = t.DisplayOrder,
                 Id = t.Id,
                 Name = t.Name,
                 NextNumber = t.NextNumber,
                 PendingCount = 0,
                 Remark = t.Remark,
                 StartCode = t.StartCode,
                 StoreId = t.StoreId
             }
            ).ToList();
            MallUtils.SetAdminRefererCookie(Url.Action("LineItemList"));
            return View(listModel);
        }

        public ActionResult EditLineItem(int id = 0)
        {
            if (id != 0)
            {
                var lineItem = LineManager.GetLineItem(id);
                return View(new EditLineItemModel
                {
                    DisplayOrder = lineItem.DisplayOrder,
                    Id = lineItem.Id,
                    Name = lineItem.Name,
                    Remark = lineItem.Remark,
                    StartCode = lineItem.StartCode
                });
            }
            else
            {
                return View(new EditLineItemModel
                {
                    DisplayOrder = 1,
                    Name = "",
                    Remark = "",
                    StartCode = ""
                });
            }
        }
        public ActionResult DeleteLineItem(int id = 0)
        {
            LineManager.DeleteLineItem(id);
            return PromptView("删除成功");
        }
        [HttpPost]
        public ActionResult SaveLineItem(EditLineItemModel model)
        {
            if (model.Id > 0)
            {
                var raw = LineManager.GetLineItem(model.Id);
                raw.Name = model.Name;
                raw.Remark = model.Remark ?? "";
                raw.StartCode = model.StartCode ?? "";
                raw.DisplayOrder = model.DisplayOrder;
                LineManager.EditLineItem(raw);
            }
            else
            {
                var newItem = new LineItem
                {
                    CurrNumber = 0,
                    DisplayOrder = model.DisplayOrder,
                    Name = model.Name,
                    NextNumber = 1,
                    Remark = model.Remark ?? "",
                    StartCode = model.StartCode ?? "",
                    StoreId = WorkContext.StoreId
                };
                LineManager.AddLineItem(newItem);
            }

            return PromptView("操作成功");
        }
        #endregion

        #region 餐位

        public ActionResult DiningTableList()
        {
            var list = new DiningTableListModel
            {
                DiningTables = DiningTableManager.GetStoreDiningTables(WorkContext.StoreId).Select(t => new DiningTableViewModel
                {
                    DiningState = t.DiningState,
                    Id = t.Id,
                    StoreId = t.StoreId,
                    TableNumber = t.TableNumber,
                    TableType = DiningTableManager.GeTableType(t.TableTypeId),
                    Name = t.Name,
                    QrCodeUrl = t.WeQrCode
                }).ToList(),
                TableTypes = DiningTableManager.GetStoreDiningTableTypes(WorkContext.StoreId)
            };
            MallUtils.SetAdminRefererCookie(Url.Action("DiningTableList"));
            return View(list);
        }

        public ActionResult EditDiningTableType(int id = -1)
        {
            var model = new DiningTableTypeModel();
            if (id <= 0) return View(model);
            var m = DiningTableManager.GeTableType(id);
            model.Id = m.Id;
            model.Name = m.Name;
            return View(model);
        }
        [HttpPost]
        public ActionResult SaveDiningTableType(DiningTableTypeModel model)
        {
            var oldmodel=DiningTableManager.GetStoreDiningTableTypes(WorkContext.StoreId);
            foreach (var item in oldmodel)
            {
                if (item.Name == model.Name)
                {
                    return PromptView("已包含此分类");
                }
            }
            if (model.Id > 0)
            {
                var old = DiningTableManager.GeTableType(model.Id);
                old.Name = model.Name;
                DiningTableManager.EditTableType(old);
            }
            else
            {
                DiningTableManager.AddTableType(new DiningTableType
                {
                    StoreId = WorkContext.StoreId,
                    Name = model.Name
                });
            }
            return PromptView("操作成功");
        }

        public ActionResult DeleteDiningTableType(int id)
        {
            if (DiningTableManager.CheckTableTypeUsing(id))
                return PromptView("删除失败，该分类底下存在餐位设置！");
            DiningTableManager.DeleteTableType(id);
            return PromptView("删除成功");
        }
        public ActionResult EditDiningTable(int id = -1)
        {
            var tps = DiningTableManager.GetStoreDiningTableTypes(WorkContext.StoreId);

            var selItems = tps.Select(t => new SelectListItem
            {
                Text = t.Name,
                Value = t.Id.ToString()
            }).ToList();
            ViewData["DiningTableTypes"] = selItems;
            var model = new DiningTableModel();
            if (id <= 0) return View(model);
            var m = DiningTableManager.GetDiningTable(id);
            model = new DiningTableModel
            {
                Id = m.Id,
                Name = m.Name,
                DiningState = m.DiningState,
                StoreId = m.StoreId,
                TableNumber = m.TableNumber,
                TableTypeId = m.TableTypeId,
            };

            return View(model);
        }
        [HttpPost]
        public ActionResult SaveDiningTable(DiningTableModel model)
        {
           var list=DiningTableManager.GetAllDiningtable(WorkContext.StoreId);
            foreach (var item in list)
            {
                if (item.Name == model.Name)
                {
                    return PromptView("餐桌号不能重复！");
                }
            }
            if (model.Id > 0)
            {
                var old = DiningTableManager.GetDiningTable(model.Id);
                old.Name = model.Name;
                old.TableTypeId = model.TableTypeId;
                old.DiningState = model.DiningState;
                old.TableNumber = model.TableNumber;
                DiningTableManager.EditDiningTable(old);
            }
            else
            {
                DiningTableManager.AddDiningTable(new DiningTable
                {
                    DiningState = model.DiningState,
                    StoreId = WorkContext.StoreId,
                    Name = model.Name,
                    TableNumber = model.TableNumber,
                    TableTypeId = model.TableTypeId
                });
            }
            return PromptView("操作成功");
        }

        public ActionResult DeleteDiningTable(int id)
        {
            DiningTableManager.DeleteDiningTable(id);
            return PromptView("删除成功");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ReNewDiningTableQrCode(int id)
        {
            var dt = DiningTableManager.GetDiningTable(id);
            var path = $"/pages/SessionCart/index?sid={id}";
            try
            {
                //采用自动打包的默认第一个
                if (StoreApplicationManager.GetStoreApplications(WorkContext.StoreId)
                        .Where(t => t.DevStatus > 1 && t.AppId == 32).ToList().Count == 0)
                {
                    return PromptView("未找到已发布上线的餐饮小程序!");
                }
                var storeAppId = StoreApplicationManager.GetStoreApplications(WorkContext.StoreId).First(t => t.DevStatus > 1 && t.AppId == 32&&t.AuthorizationId>0)?.StoreAppId ?? 0;
                var filename = WxQRCode.GetWxaCodeByStoreAppId(WorkContext.StoreId, path, storeAppId);
                if (string.IsNullOrEmpty(filename))
                    return PromptView("获取二维码文件失败!");
                var redirectUrl = $"http://static.711688.net.cn/upload/user/{filename}";
                dt.WeQrCode = redirectUrl;
                DiningTableManager.EditDiningTable(dt);
                return PromptView("二维码成功生成！！");

            }
            catch (Exception e)
            {

                return PromptView($"获取二维码文件失败!{e.Message}");
            }
        }
        #endregion

        #region 餐桌二维码打印

        public ActionResult PrintDiningTableQrCode(int id)
        {
            var dt = DiningTableManager.GetDiningTable(id);
            if (dt == null)
                return Content(GetFailJson("找不到记录！"));

            if (string.IsNullOrEmpty(dt.WeQrCode))
                return Content(GetFailJson("请先生成餐桌二维码！"));

            var number = $"餐位 {dt.TableNumber}";
            //二维码目录
            var codeDir = WeiXin.Sdk.WeiXinSdk.GetMapPath("/upload/user/");
            var codePath = $"{codeDir}acode_{DateTime.Now:yyMMddHHmmssfffffff}.jpg";
            var codeUrl = dt.WeQrCode;
            //二维码模板目录
            var templateDir = WeiXin.Sdk.WeiXinSdk.GetMapPath("/admin_store/images/template/");
            var templatePath = $"{templateDir}QrCode.jpg";
            //合成的二维码名
            var printFileName = $"acode_{DateTime.Now:yyMMddHHmmssfffffff}_print.jpg";
            var printUrl = $"/upload/user/{printFileName}";

            //下载二维码
            new Core.Http.HttpRequest().DownLoadImage(codeUrl, codePath);

            //合成图片
            WxQRCode.SynthesisDiningQrCode(templatePath, codePath, number, string.Format("{0}{1}", codeDir, printFileName));
            return Content(GetSuccessJson(printUrl));
        }

        string GetFailJson(string msg)
        {
            var json = new
            {
                Code=501,
                Message=msg,
                Data=string.Empty
            };
            return Newtonsoft.Json.JsonConvert.SerializeObject(json);
        }
        string GetSuccessJson(string data)
        {
            var json = new
            {
                Code = 0,
                Message = string.Empty,
                Data = data
            };
            return Newtonsoft.Json.JsonConvert.SerializeObject(json);
        }
        #endregion
    }
}
